package com.cdn.allmobilestore.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.cdn.allmobilestore.R;
import com.cdn.allmobilestore.activity.BaseActivity;
import com.cdn.allmobilestore.activity.DetailActivity;
import com.cdn.allmobilestore.adapter.ListAppAdapter;
import com.cdn.allmobilestore.loader.BaseLoader;
import com.cdn.allmobilestore.loader.SearchLoader;
import com.cdn.allmobilestore.loader.SearchLoader.Result;
import com.cdn.allmobilestore.model.AppInfo;
import com.cdn.allmobilestore.model.ListAppInfo;
import com.cdn.allmobilestore.ulti.Constant;
import com.cdn.allmobilestore.ulti.Log;
import com.cdn.allmobilestore.widget.EmptyLoadingView;
import com.cdn.allmobilestore.widget.SearchBar;

public class SearchFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<SearchLoader.Result> 
{
	SearchBar mSearchBar;
	CharSequence searchKey = "";
	EmptyLoadingView loading;
	private static final int SEARCH_LOADER = 0;
	private ListAppAdapter mListAppAdapter;
	private ListView mListView;
	private ListView mSearchHistoryListView;
	private String[] searchHistory;
	List<String> list_search_history = new ArrayList<String>();
	JSONArray jsearch_history = new JSONArray();
	
	private AdapterView.OnItemClickListener mItemClickListner = new AdapterView.OnItemClickListener()
	  {
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	    {
	    	if (position < SearchFragment.this.mListView.getChildCount());
	        {
	        	AppInfo appInfo = (AppInfo)SearchFragment.this.mListAppAdapter.getItem(position);
	        	Intent intent = new Intent(SearchFragment.this.getActivity(),DetailActivity.class);
	        	intent.putExtra(Constant.INTENT_EXTRA_APP_ID, appInfo.getId());
	            intent.putExtra(Constant.INTENT_EXTRA_APP_NAME, appInfo.getName());
	            intent.putExtra(Constant.INTENT_EXTRA_APP_CAT, appInfo.getCategory());
	            intent.putExtra(Constant.INTENT_EXTRA_APP_SIZE, appInfo.getSize());            
	            intent.putExtra(Constant.INTENT_EXTRA_APP_AGENCY, appInfo.getCompanyName());
	            intent.putExtra(Constant.INTENT_EXTRA_APP_ICON, appInfo.getIconLink());
	            //intent.putExtra(Constant.INTENT_EXTRA_APP_RATE, appInfo.get);
	            
	            SearchFragment.this.getActivity().startActivity(intent);
	            SearchFragment.this.getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.disappear);
	            Log.v("click");
	        }
	    }
	  };
	  
	
    public View onCreateView(LayoutInflater inflate, ViewGroup viewgroup, Bundle bundle)
    {
    	DisplayMetrics metrics = new DisplayMetrics();  
    	SearchFragment.this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    	View view = inflate.inflate(R.layout.search_fragment, viewgroup,false);
    	this.loading = (EmptyLoadingView)view.findViewById(R.id.loading);
    	this.mListView = ((ListView)view.findViewById(R.id.list_view));
    	this.mListView.setVisibility(View.GONE);
    	this.mSearchHistoryListView = ((ListView)view.findViewById(R.id.search_history_list_view));
    	this.mSearchHistoryListView.setScrollContainer(false);
        this.mListAppAdapter = new ListAppAdapter(getActivity(),metrics);
        this.mListView.setAdapter(this.mListAppAdapter);
        this.mListView.setOnItemClickListener(this.mItemClickListner);
    	this.mSearchBar = (SearchBar)view.findViewById(R.id.searchBar);
    	this.mSearchBar.enableSearchBack(true, (BaseActivity) SearchFragment.this.getActivity());
    	this.mSearchBar.addTextChangedListener(new TextWatcher() {
		     
		    @Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        SearchFragment.this.searchKey = cs;
		        if(arg3 == 0)
		        {
		        	ArrayList<AppInfo> data = new ArrayList<AppInfo>();
		        	SearchFragment.this.mListAppAdapter.updateData(data);	
		        	SearchFragment.this.mListView.setVisibility(View.GONE);
		        	SearchFragment.this.mSearchHistoryListView.setVisibility(View.VISIBLE);
		        	SearchFragment.this.loading.setEmptyText("");
		        	SearchFragment.this.loading.stopLoading(false,false);
		        }		        
		    }
		     
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) {}
		     
		    @Override
		    public void afterTextChanged(Editable arg0) {
		        // TODO Auto-generated method stub                          
		    }
		    
		    
		});
    	
    	EditText.OnEditorActionListener txtListener = new EditText.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {			
				performSearch();							
				return false;
			}
		};
   
		this.mSearchBar.setOnEditorActionListener(txtListener);
		this.mSearchBar.focusSearchBox();
		
		SharedPreferences prefs = SearchFragment.this.getActivity().getSharedPreferences(Constant.STRING_PREFERENCE, Context.MODE_PRIVATE);
		String search_history = prefs.getString(Constant.STRING_PREFERENCE_SEARCH_HISTORY, null);
		if(search_history != null && !search_history.equals(""))
		{
			try {
			    jsearch_history = new JSONArray (search_history);  			    
			    for (int i=0; i<jsearch_history.length(); i++) {
			    	list_search_history.add( jsearch_history.getString(i) );			    				   
			    }
			    Collections.reverse(list_search_history);
			    
			} catch (JSONException e) {
			    e.printStackTrace();
			}
			
		}
		
		if(list_search_history.size() > 0)
		{
			mSearchHistoryListView.setAdapter(new ArrayAdapter<String>(SearchFragment.this.getActivity(), android.R.layout.simple_list_item_1, list_search_history) {

		            @Override
		            public View getView(int position, View convertView, ViewGroup parent) {

		                // setting the ID and text for every items in the list
		                String text = getItem(position);
		                
		                // visual settings for the list item
		                TextView listItem = new TextView(SearchFragment.this.getActivity());
		                listItem.setText(text);		                
		                listItem.setTextSize(12);
		                listItem.setPadding(20,10,10,10);		                		                
		                return listItem;
		            }
		       
		    });
			
			 this.mSearchHistoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
			  {
			    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			    {
			    	SearchFragment.this.searchKey = SearchFragment.this.list_search_history.get(position);
			    	if( SearchFragment.this.searchKey!= null)
			    	{
			    		SearchFragment.this.mSearchBar.setText(SearchFragment.this.searchKey);
			    		performSearch();
			    	}
			    }
			  });
		}
		
        return view;
    }
    
    
    public void performSearch()
    {
    	SearchFragment.this.mListView.setVisibility(View.VISIBLE);
		if (getLoaderManager().getLoader(SEARCH_LOADER) == null) {
			getLoaderManager().initLoader(SEARCH_LOADER, null, SearchFragment.this);
	    } else {
	    	getLoaderManager().restartLoader(SEARCH_LOADER, null, SearchFragment.this);
	    }
    }
    
    public void onActivityCreated(Bundle paramBundle)
    {
        super.onActivityCreated(paramBundle);
    
    }
    
    @Override
    public void onStart(){
        super.onStart();
        
    }

	@Override
	public Loader onCreateLoader(int arg0, Bundle arg1) {
		if (arg0 == SEARCH_LOADER)
	      {
	        this.mLoader = new SearchLoader(getActivity());
	        ((SearchLoader)this.mLoader).setsearchKey(SearchFragment.this.searchKey);
	        this.mLoader.setProgressNotifiable(this.loading);
	      }
	  	 BaseLoader baseLoader = this.mLoader; 	      
	     return baseLoader;		
	}




	@Override
	public void onLoadFinished(Loader<Result> arg0, Result arg1) {
		
		this.mListView.setVisibility(View.VISIBLE);
		this.mSearchHistoryListView.setVisibility(View.GONE);
			
		
		if(arg1.mTopAppInfos != null)
		{			
			this.mListAppAdapter.updateData(arg1.mTopAppInfos);	
			SharedPreferences prefs = SearchFragment.this.getActivity().getSharedPreferences(Constant.STRING_PREFERENCE, Context.MODE_PRIVATE);
			Editor e = prefs.edit();
			//list_search_history.add((String) SearchFragment.this.searchKey);
			boolean isExist = false;
			for (int i=0; i<jsearch_history.length(); i++) {
		    	try {		    		
					if(jsearch_history.getString(i).trim().equals(SearchFragment.this.searchKey.toString().trim()))
					{
						Log.v("history containt search key");
						isExist =  true;
						break;
					}
						
					
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}			    				   
		    }
			if(!isExist)
			{
				list_search_history.add(SearchFragment.this.searchKey.toString().trim());
				jsearch_history.put(SearchFragment.this.searchKey.toString().trim());
			}
					
			
			e.putString(Constant.STRING_PREFERENCE_SEARCH_HISTORY, jsearch_history.toString());
			e.commit();
			
			if((ArrayAdapter<String>)this.mSearchHistoryListView.getAdapter() != null)
				((ArrayAdapter<String>)this.mSearchHistoryListView.getAdapter()).notifyDataSetChanged();
		}
		else
			this.loading.setEmptyText(getResources().getString(R.string.data_error));
			this.loading.stopLoading(false,false);
			
	}




	@Override
	public void onLoaderReset(Loader<Result> arg0) {
		((SearchLoader)this.mLoader).setsearchKey(SearchFragment.this.searchKey);
		
	}
    
    
}